//
//  JsonAnimation.swift
//  KaiChat
//
//  Created by lx on 2023/11/1.
//

import UIKit
import Lottie

class JsonAnimationView: UIView {
    
    @objc public var animationView: LottieAnimationView?
    @objc public var fileName: String?
    
    @objc public var isLoop = false
 
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    @objc public convenience init(name: String) {
        self.init(frame: .zero)
        fileName = name
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if let animationView = animationView {
            animationView.frame = self.bounds
        }
    }
    
    @objc public func play(complete: @escaping (Bool) -> Void) -> Void {
        if let animationView = animationView, animationView.isAnimationPlaying {
            animationView.stop()
            animationView.removeFromSuperview();
            return
        }
        
//        DispatchQueue.global().async {
            let animation = LottieAnimation.named(self.fileName!, bundle: Bundle.main, subdirectory: nil, animationCache: nil)
            let provider = BundleImageProvider(bundle: Bundle.main, searchPath: nil)
            
//            DispatchQueue.main.async {
                self.animationView = LottieAnimationView(animation: animation, imageProvider:provider)
                if let animationView = self.animationView {
                    if (isLoop) {
                        animationView.loopMode = .loop
                    } else {
                        animationView.loopMode = .playOnce
                    }
                    self.addSubview(animationView)
                    animationView.play(completion: complete)
                }
//            }
//        }
        
    }
    
    @objc public func pause() -> Void {
        animationView?.pause();
    }
    
    @objc public func stop() -> Void {
        animationView?.stop();
    }
    
}
